package com.easycamera.adapter

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aj.easylibrary.net.RetrofitServiceManager
import com.bumptech.glide.Glide
import com.easycamera.R
import com.easycamera.adapter.FrameAdapter.FrameHolder
import com.easycamera.bean.FrameInfo
import com.easycamera.net.ApiService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okio.BufferedSink
import okio.Okio
import java.io.File


class FrameAdapter(private val context: Context, private val data: List<FrameInfo>) : RecyclerView.Adapter<FrameHolder>() {
    private var selected = 0
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FrameHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.frame_item_layout,
                parent, false)
        val viewHolder = FrameHolder(view)
        viewHolder.thumbImage = view
                .findViewById<View>(R.id.frame_thumb_image) as ImageView
        viewHolder.frameName = view
                .findViewById<View>(R.id.frame_thumb_name) as TextView
        viewHolder.frameRoot = view
                .findViewById<View>(R.id.frame_root) as FrameLayout
        viewHolder.thumbSelected = view
                .findViewById<View>(R.id.frame_thumb_selected) as FrameLayout
        viewHolder.thumbSelected_icon = view.findViewById(R.id.frame_thumb_selected_icon)
        viewHolder.thumbDownload_icon = view.findViewById(R.id.frame_thumb_download_icon)


        return viewHolder
    }

    override fun onBindViewHolder(holder: FrameHolder, position: Int) {
        val info = data[position]
        if (info.url.isNotEmpty()) {
            Glide.with(holder.itemView.context)
                    .load(info.url)
                    .into(holder.thumbImage!!)
        } else {
            Glide.with(holder.itemView.context)
                    .load(info.url)
                    .into(holder.thumbImage!!)
        }
        holder.frameName?.text = info.name

        if (position == selected) {
            holder.thumbSelected!!.visibility = View.VISIBLE

            if (position == 0) {
                //第一个，取消边框选项
                holder.thumbDownload_icon?.visibility = View.GONE
                holder.thumbSelected_icon?.visibility = View.VISIBLE

            } else {

                if (info.hasDownload) {
                    //已下载，显示选择icon
                    holder.thumbSelected_icon?.visibility = View.VISIBLE
                    holder.thumbDownload_icon?.visibility = View.GONE

                } else {
                    holder.thumbDownload_icon?.text = "点击下载"
                    holder.thumbDownload_icon?.visibility = View.VISIBLE
                    holder.thumbSelected_icon?.visibility = View.GONE

                }
            }
        } else {
            holder.thumbSelected!!.visibility = View.GONE
        }


        holder.frameRoot?.setOnClickListener(View.OnClickListener {
            val lastSelected = selected
            selected = position
            if (position == 0 || info.hasDownload) {
                onFrameChangeListener?.onFrameChanged(info, position)
            } else {
                //开始下载
                if (lastSelected == selected) {
                    val builder = AlertDialog.Builder(context)
                    builder.setMessage("确认下载么？")
                            .setPositiveButton("Yes", object : DialogInterface.OnClickListener {
                                @SuppressLint("CheckResult")
                                override fun onClick(dialog: DialogInterface?, which: Int) {
                                    dialog?.dismiss()
                                    holder.thumbDownload_icon?.text = "download..."
                                    RetrofitServiceManager.getInstance().creat(ApiService::class.java)
                                            .downloadFileWithDynamicUrlSync(info.url)
                                            .subscribeOn(Schedulers.io())
                                            .map { response ->
                                                val filename = info.url.substring(info.url.lastIndexOf("/") + 1, info.url.length)
                                                val file = File("/data/data/" + holder.itemView.context.packageName.toString() + "/frames")
                                                if (!file.exists()) {
                                                    file.mkdirs()
                                                }
                                                val destinationFile = File("/data/data/" + holder.itemView.context.packageName.toString() + "/frames/" + filename)
                                                if (destinationFile.exists()) {
                                                    destinationFile.delete()
                                                }
                                                val bufferedSink: BufferedSink = Okio.buffer(Okio.sink(destinationFile))
                                                bufferedSink.writeAll(response.body()?.source())
                                                bufferedSink.close()
                                                destinationFile.absolutePath

                                            }
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe({ file ->
                                                Log.i("xx", "${file}")
                                                notifyItemChanged(lastSelected)
                                                info.hasDownload = true
                                                info.localFileUrl = file

                                                onFrameChangeListener?.onFrameChanged(info, position)


                                            }, {

                                            })
                                }

                            })
                            .setNeutralButton("No", object : DialogInterface.OnClickListener {
                                override fun onClick(dialog: DialogInterface?, which: Int) {
                                    dialog?.dismiss()
                                }

                            }).show()
                }


            }


            notifyItemChanged(lastSelected)
            notifyItemChanged(position)
        })

    }

    override fun getItemCount(): Int {
        return data.size
    }

    inner class FrameHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
        var thumbImage: ImageView? = null
        var frameName: TextView? = null
        var thumbSelected: FrameLayout? = null

        var frameRoot: FrameLayout? = null
        var thumbSelected_icon: View? = null
        var thumbDownload_icon: TextView? = null

    }

    interface OnFrameChangeListener {
        fun onFrameChanged(info: FrameInfo, position: Int)
    }

    private var onFrameChangeListener: OnFrameChangeListener? = null

    fun setOnFrameChangeListener(listener: OnFrameChangeListener) {
        this.onFrameChangeListener = listener
    }

}